package com.night.test;

import com.night.annotation.Component;
import com.night.annotation.Order;
import com.night.context.BeanPostProcessor;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: chen yang
 * @Date: 2024/12/1 10:51
 */
@Component
@Order(100)
public class ProxyBeanPostProcessor implements BeanPostProcessor {

    Map<String, Object> originBeans = new HashMap<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if (OriginBean.class.isAssignableFrom(bean.getClass())) {
            System.out.printf("----------- create first proxy for bean '%s': %s%n", beanName, bean);
            var proxy = new ProxyBean((OriginBean) bean);
            originBeans.put(beanName, bean);
            return proxy;
        }
        return bean;
    }

    @Override
    public Object postProcessOnSetProperty(Object bean, String beanName) {
        Object origin = originBeans.get(beanName);
        if (origin != null) {
            System.out.printf("----------- auto set property for %s from first proxy %s to origin bean: %s%n", beanName, bean, origin);
            return origin;
        }
        return bean;
    }
}
